<!-- 异常处理界面 -->
<template>
	<view>
		<view class="circle">
			<!-- <view class="houseId row-center">
				{{show_nfcId ? '鸽舍号：'+ show_nfcId : '鸽舍号'}}
			</view> -->
			<view class="ul">
				<view class="li ycd_bg ycd_color_left" v-for="item in cageCount" :key="item">
					<view class="left">
						<span class="cageId">{{item}}</span>
						<button class="statu" :disabled="exp_show.length > 0 ? !exp_show[item - 1].length > 0 : false"
							:class="exp_show.length > 0 ? 'notDisabled' : 'disabled'"
							@click="submit(item)">一键处理</button>
					</view>
					<view class="right">
						<view class="expection" v-for="(ite,index) in exp_show.length > 0 ? exp_show[item - 1] : []" :key="index">{{ite}}</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 顶部提示 -->
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	import {
		getNowDate
	} from '@/getTime.js'
	import {
		reqGetExp,
		reqExpection
	} from '@/api/index.js';
	import {
		mapGetters
	} from 'vuex'

	export default {
		data() {
			return {
				formData: {
					siteId: uni.getStorageSync('siteId'),
					houseId: '',
					cageId: '',
					updateTime: '',
					oneOrAll: 1
				},
				exp: [],
				exp_show:[],
				disabled: false,
				loading: false,
				test: [''],
				cageCount: 6, // 默认6个鸽笼，与其他页面保持一致
				isLoading: false
			}
		},
		watch: {
			nfcId(newValue, oldValue) {
				if(newValue !== oldValue){
					this.getCageCount();
					this.getExp();
				}
			},
			// 监听 cageStatu 变化，动态更新鸽笼数量
			cageStatu: {
				handler(newVal) {
					if (newVal && newVal.length > 0) {
						this.cageCount = newVal.length;
						console.log('异常处理页面 - cageStatu 变化，鸽笼数量:', this.cageCount);
						// 确保异常数据数组与鸽笼数量匹配
						this.adjustExpDataToCageCount();
					}
				},
				immediate: true,
				deep: true
			}
		},
		async mounted() {
			await this.getCageCount();
			await this.getExp();
		},
		onShow() {
			this.getCageCount();
		},
		computed: {
			...mapGetters(['nfcId', 'show_nfcId', 'cageStatu']),
		},
		onPullDownRefresh() {
			this.getExp();
		},
		methods: {
			// 获取鸽笼数量 - 使用与调仔页面相同的方式
			async getCageCount() {
				this.isLoading = true;
				try {
					const obj = {
						siteId: uni.getStorageSync('siteId'),
						houseId: this.nfcId,
					}
					console.log('异常处理页面 - 获取鸽笼状态参数:', obj);
					
					// 使用与调仔页面相同的方法获取鸽笼状态
					await this.$store.dispatch('getStatu', obj);
					
					// 从 Vuex getters 中获取 cageStatu，它的长度就是实际的鸽笼数量
					const cageStatu = this.$store.getters.cageStatu;
					
					if (cageStatu && cageStatu.length > 0) {
						this.cageCount = cageStatu.length;
						console.log('异常处理页面 - 实际鸽笼数量:', this.cageCount);
					} else {
						this.cageCount = 6; // 如果没有数据，默认显示6个
						console.warn('异常处理页面 - 未获取到鸽笼状态数据，使用默认数量:', this.cageCount);
					}
					
				} catch (error) {
					console.error('获取鸽笼数量失败:', error);
					this.cageCount = 6; // 失败时使用默认数量
					this.$refs.uToast.show({
						title: '获取鸽笼数据失败',
						type: 'error',
						duration: 1500,
						position: 'top'
					});
				} finally {
					this.isLoading = false;
				}
			},
			
			// 调整异常数据数组长度以匹配鸽笼数量
			adjustExpDataToCageCount() {
				if (this.exp.length < this.cageCount) {
					// 如果异常数据少于鸽笼数量，用空数组补齐
					this.exp = [...this.exp, ...new Array(this.cageCount - this.exp.length).fill([])];
				} else if (this.exp.length > this.cageCount) {
					// 如果异常数据多于鸽笼数量，截取前cageCount个
					this.exp = this.exp.slice(0, this.cageCount);
				}
				
				if (this.exp_show.length < this.cageCount) {
					// 如果显示数据少于鸽笼数量，用空数组补齐
					this.exp_show = [...this.exp_show, ...new Array(this.cageCount - this.exp_show.length).fill([])];
				} else if (this.exp_show.length > this.cageCount) {
					// 如果显示数据多于鸽笼数量，截取前cageCount个
					this.exp_show = this.exp_show.slice(0, this.cageCount);
				}
			},
			
			getExp() {
				const obj = {
					siteId: this.formData.siteId,
					houseId: this.nfcId
				}
				// 获取异常状态
				this.disabled = false
				this.loading = true
				reqGetExp(obj).then(data => {
					if (data.code === 200) {
						// 确保异常数据数组长度与鸽笼数量匹配
						let abnormalData = data.abnormal || [];
						if (abnormalData.length < this.cageCount) {
							// 如果返回的数据少于鸽笼数量，用空数组补齐
							abnormalData = [...abnormalData, ...new Array(this.cageCount - abnormalData.length).fill([])];
						} else if (abnormalData.length > this.cageCount) {
							// 如果返回的数据多于鸽笼数量，截取前cageCount个
							abnormalData = abnormalData.slice(0, this.cageCount);
						}
						
						this.exp = abnormalData;
						
						// 对接受来的异常进行遍历 只显示淘汰和种鸽死亡
						const filteredAndModifiedAbnormal = abnormalData.map(subArray => 
						    subArray.map(item => {
						        if (item.includes("死亡")) {
						            let part = item.split(';').find(part => part.includes("种鸽"));
						            return part ? part.trim() : item;
						        } else {
						            return item;
						        }
						    })
						);
						this.exp_show = filteredAndModifiedAbnormal;
						console.log('异常数据显示:', filteredAndModifiedAbnormal);
					} else if (data.code === 404) {
						// 当返回数组为空时，无异常
						this.disabled = true
						// 初始化空数组
						this.exp = new Array(this.cageCount).fill([]);
						this.exp_show = new Array(this.cageCount).fill([]);
						this.$refs.uToast.show({
							title: data.msg,
							type: 'warning',
							duration: "800",
							position: "top"
						})
					}
				}).catch((e) => {
					console.log(e);
					this.$refs.uToast.show({
						title: '网络连接失败',
						type: 'warning',
						duration: '1000',
						position: 'top'
					})
				})
				.finally(() => {
					this.loading = false
					uni.stopPullDownRefresh()
				})
			},
			
			submit(cageId) {
				// 检查cageId是否在有效范围内
				if (cageId < 1 || cageId > this.cageCount) {
					this.$refs.uToast.show({
						title: '无效的鸽笼编号',
						type: 'warning',
						duration: '800',
						position:'top'
					})
					return;
				}
				
				this.$loading()
				this.formData.houseId = this.nfcId
				this.formData.cageId = cageId
				this.formData.updateTime = getNowDate()
				this.formData.refer = this.exp[cageId - 1] || [];
				reqExpection(this.formData).then(data => {
					if (data.code == 200) {
						this.getExp()
						this.$refs.uToast.show({
							title: data.msg,
							type: 'success',
							duration: '800',
							position: 'top',
						})
					} else {
						this.$refs.uToast.show({
							title: data.msg,
							type: 'warning',
							duration: '800',
							position:'top'
						})
					}
				}).catch(() => {
					this.$refs.uToast.show({
						title: '操作失败',
						type: 'error',
						duration: '800',
						position:'top'
					})
				}).finally(() => {
					this.$hide()
				})
			},
			
			testNFC() {
				return true;
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import 'styles/builder.scss';

	.checked_border {
		background-color: #fff;
		color: lawngreen;
		border: 2px solid greenyellow;
	}

	.disabled {
		color: gray;
		background-color: darkgray;
	}

	.notDisabled {
		color: #fff;
		background-color: #4472c4;
	}

	.ycd_bg {
		background-color: #dbe2f1;
	}

	.ycd_color {
		color: #4472c4
	}

	.ycd_color_left {
		color: #7d9ad2;
		border-right: 2px solid #7c9bd2;
	}

	.ycd_button_right {
		color: #dbe2f1;
		background-color: #7c9bd2;
	}

	.other_bg {
		background-color: #7c9bd2;
	}

	.other_color_left {
		color: #dbe2f1;
		border-right: 2px solid #dbe2f1;
	}

	.other_button_right {
		color: #7c9bd2;
		background-color: #dbe2f1;
	}

	.houseId {
		width: 100%;
		margin: 10rpx auto;
		padding: 18.12rpx 18.12rpx;
		font-size: 39.86rpx;
		border-radius: 14.49rpx;
		color: #fff;
		background-color: #7d9ad2;
	}

	.circle {
	  width: 100%;
	  height: 100vh;
	  padding: 20rpx;

		h1 {
			text-align: center;
			font-weight: 700;
		}

		.ul {
		  display: flex;
		  flex-direction: row;
		  flex-wrap: wrap;
		  justify-content: space-around;
		  align-content: flex-start;
		  width: 100%;
		  gap: 20rpx;
		  margin: 0;
		  padding: 0;
		
		.li {
		  width: 45%; 
		  display: flex;
		  text-align: center;
		  border-radius: 20rpx;
		  min-height: 200rpx; 
		  margin-bottom: 20rpx;

				.left,
				.right {
					display: flex;
					flex-direction: column;
					justify-content: space-around;
					height: 90%;
					font-weight: bold;
				}

				.left {
					width: 40%;
					justify-content: center;
					padding-right: 10rpx;
					box-sizing: border-box;
					border-right: 2px solid #4472c4;
					box-sizing: border-box;

					.cageId {
						font-size: 91.41rpx
					}

					.statu {
						font-size: 20rpx;
						font-weight: bold;
						border-radius: 10rpx;
						box-sizing: border-box;
					}
				}

				.right {
					width: 60%;
					display: flex;
					justify-content: space-around;
					align-content: space-around;
					flex-wrap: wrap;

					.expection {
						width: 100%;
						height: auto;
						overflow: hidden;
						word-wrap: break-word;
						font-size: 18.29rpx;
						font-weight: bold;
						border-radius: 10rpx;
						box-sizing: border-box;
						color: #4472c4
					}
				}
			}
		}
	}

	.abnormal {
		@include flex(space-around, center, 'items') width: 70%;
		height: 120rpx;
		margin: 0 auto;
		padding: 20rpx 57.97rpx;
		font-size: 38.04rpx;
		font-weight: 700;
		color: #fff;
		box-shadow: 9px 4px 10px 0 #7d9ad2;
		background-color: #7d9ad2;
	}
</style>